package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoardService;
import com.example.forum.services.IUserService;
import com.example.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private IBoardService boardService;
    @Autowired
    private IUserService userService;

    @Override
    public void create(Article article) {
        //非空校验
        if(null==article || null==article.getUserId()
        || StringUtil.isEmpty(article.getTitle())
        || StringUtil.isEmpty(article.getContent())){
            log.warn("参数校验失败! article = {}",article);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setVisitCount(0); //访问
        article.setReplyCount(0); //回复
        article.setLikeCount(0); //点赞
        article.setDeleteState((byte) 0);
        article.setState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        int row = articleMapper.insertSelective(article);
        if(row<=0){
            log.error("新增帖子失败! article = {}",article);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新用户的发帖数
        User user = userService.selectById(article.getUserId());
        if(null==user){
            log.warn("找不到当前帖子的发表用户! id:{}",article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        userService.addOneArticleCountById(user.getId());

        //更新板块信息
        Board board = boardService.selectById(article.getBoardId());
        if(null==board){
            log.warn("找不到当前帖子的发表板块! id:{}",article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        boardService.addOneArticleCountById(board.getId());

        //发帖成功!
        log.info("发送新帖子成功! userId:{} , boardId:{} , articleId:{}",
                user.getId(),board.getId(),article.getId());
    }

    @Override
    public List<Article> selectAll() {
        //DAO
        return articleMapper.selectAll();
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        if(null==boardId){
            log.warn("没有传入必要的板块id,boardId:{}",boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //检验板块是否存在
        Board board = boardService.selectById(boardId);
        if(null==board) {
            log.warn("当前板块不存在,boardId:{}",boardId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXIST));
        }
        return articleMapper.selectAllByBoardId(boardId);
    }

    @Override
    public Article selectDetailById(Long id) {
        //非空校验
        if(null==id || id<=0){
            log.warn("参数有误! id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //DAO
        Article article = articleMapper.selectDetailById(id);
        if(null == article){
            log.error("当前帖子不存在或已被删除! id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXIST));
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.error("修改信息失败,当前修改信息为帖子的访问量,id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

        //返回也要更新
        article.setVisitCount(article.getVisitCount()+1);
        return article;
    }

    @Override
    public Article selectById(Long id) {
        if(null==id){
            log.warn("参数校验为空! articleId:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return articleMapper.selectByPrimaryKey(id);
    }

    @Override
    public void modify(Long id, String title, String content) {
        //校验参数
        if(null==id || StringUtil.isEmpty(title) || StringUtil.isEmpty(content)){
            log.warn("修改帖子时参数错误,id:{},title:{}",id,title);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构建更新对象
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row !=1 ){
            log.error("更新帖子失败,id:{},title:{}",id,title);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_UPDATE));
        }
    }

    @Override
    public void thumbsUpById(Long id) {
        if(null==id || id <= 0){
            log.warn("修改帖子时参数错误,id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if(null== article || article.getDeleteState()==1 ){
            log.warn("帖子状态异常! articleId:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXIST));
        }
        if(article.getState() ==1){
            log.warn("帖子状态异常! articleId:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.ARTICLE_IS_BANNED));
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row !=1 ){
            log.error("点赞失败,id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_UPDATE));
        }
    }

    @Override
    public void deleteById(Long id) {
        if(null == id || id<=0){
            log.warn("被删除帖子的d传入为空!, id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if(null==article || article.getDeleteState()==1){
            log.warn("当前帖子不存在! id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXIST));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.error("删除用户帖子失败失败!,articleId:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_DELETE));
        }
        boardService.subOneArticleCountById(article.getBoardId());
        userService.subOneArticleCountById(article.getUserId());
        log.info("删除帖子成功! articleId:{} userId:{} boardId:{}",article.getId(),article.getUserId(),article.getBoardId());
    }

    @Override
    public void addOneReplyCountById(Long id) {
        if(null == id || id<=0){
            log.warn("被回复帖子的d传入为空!, id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //获取帖子信息
        Article article = articleMapper.selectByPrimaryKey(id);
        if(null==article || article.getDeleteState()==1){
            log.warn("当前帖子不存在! id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXIST));
        }
        //帖子已被禁止操作
        if(article.getState()==1){
            log.warn("当前帖子状态异常! id:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.ARTICLE_IS_BANNED));
        }
        //构造更新对象
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if(row!=1){
            log.error("回复用户帖子失败!articleId:{}",id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_REPLY));
        }
    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if(null == userId || userId<=0){
            log.warn("传入的用户id不正确! userId:{}",userId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userService.selectById(userId);
        if(null==user||user.getDeleteState()==1){
            log.warn("当前用户不存在! userId:{}",user);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
         //DAO
        //return
        return articleMapper.selectByUserId(userId);
    }
}
